#include "kill.h"

#include <stdlib.h>
#include <stdio.h>

#include <SDL2/SDL.h>

static kill_callback *callbacks = NULL;
static size_t total_callbacks = 0;
static size_t used_callbacks = 0;

int kill_init(size_t expected_callbacks) {
	if (callbacks) return -1;

	callbacks = malloc(sizeof(kill_callback) * expected_callbacks);

	total_callbacks = expected_callbacks;
	used_callbacks = 0;

	return !!callbacks;
}

int kill_push(kill_callback callback) {
	if (!callbacks) return 0;
	if (used_callbacks >= total_callbacks) return 0;

	callbacks[used_callbacks++] = callback;
}

void kill(int exit_status) {
	if (callbacks) {
		/* Run callbacks in inverse order */
		for (size_t i = used_callbacks; i --> 0;) {
			callbacks[i]();
		}
		free(callbacks);
	}
	exit(exit_status);
}

void kill_sdl(const char *message, int exit_status) {
	printf("%s: %s\n", message, SDL_GetError());
	kill(exit_status);
}
